<template>
  <div class="author-list">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>作者管理</h2>
    </div>

    <!-- 搜索和操作区域 -->
    <div class="search-section">
      <el-row :gutter="20">
        <el-col :span="16">
          <el-form :model="searchForm" :inline="true" class="search-form">
            <el-form-item label="作者姓名">
              <el-input
                v-model="searchForm.name"
                placeholder="请输入作者姓名"
                clearable
                @keyup.enter="handleSearch"
              />
            </el-form-item>
            <el-form-item label="国籍">
              <el-input
                v-model="searchForm.nationality"
                placeholder="请输入国籍"
                clearable
                @keyup.enter="handleSearch"
              />
            </el-form-item>
            <el-form-item label="状态">
              <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
                <el-option label="正常" :value="1" />
                <el-option label="禁用" :value="0" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSearch">
                <el-icon><Search /></el-icon>
                搜索
              </el-button>
              <el-button @click="handleReset">
                <el-icon><Refresh /></el-icon>
                重置
              </el-button>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="8" class="text-right">
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            添加作者
          </el-button>
          <el-button
            type="danger"
            :disabled="selectedRows.length === 0"
            @click="handleBatchDelete"
          >
            <el-icon><Delete /></el-icon>
            批量删除
          </el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 数据表格 -->
    <div class="table-section">
      <el-table
        v-loading="loading"
        :data="tableData"
        @selection-change="handleSelectionChange"
        stripe
        border
      >
        <el-table-column type="selection" width="50" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="作者姓名" min-width="120" />
        <el-table-column prop="nationality" label="国籍" width="100" />
        <el-table-column prop="email" label="邮箱" min-width="180" />
        <el-table-column prop="website" label="个人网站" min-width="200" show-overflow-tooltip />
        <el-table-column prop="birthDate" label="出生日期" width="120">
          <template #default="{ row }">
            {{ formatDate(row.birthDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="160">
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleView(row)">
              <el-icon><View /></el-icon>
              查看
            </el-button>
            <el-button type="warning" size="small" @click="handleEdit(row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-section">
      <el-pagination
        v-model:current-page="pagination.pageNum"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 查看详情对话框 -->
    <el-dialog
      v-model="viewDialogVisible"
      title="作者详情"
      width="600px"
    >
      <div v-if="currentAuthor" class="author-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="作者姓名">{{ currentAuthor.name }}</el-descriptions-item>
          <el-descriptions-item label="国籍">{{ currentAuthor.nationality }}</el-descriptions-item>
          <el-descriptions-item label="邮箱">{{ currentAuthor.email }}</el-descriptions-item>
          <el-descriptions-item label="个人网站">
            <a v-if="currentAuthor.website" :href="currentAuthor.website" target="_blank">
              {{ currentAuthor.website }}
            </a>
            <span v-else>-</span>
          </el-descriptions-item>
          <el-descriptions-item label="出生日期">{{ formatDate(currentAuthor.birthDate) }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="currentAuthor.status === 1 ? 'success' : 'danger'">
              {{ currentAuthor.status === 1 ? '正常' : '禁用' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="作者简介" :span="2">
            <div class="biography">{{ currentAuthor.biography || '-' }}</div>
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <el-button @click="viewDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, Delete, View, Edit } from '@element-plus/icons-vue'
import authorApi from '@/api/author'

const router = useRouter()

// 响应式数据
const loading = ref(false)
const tableData = ref([])
const selectedRows = ref([])
const viewDialogVisible = ref(false)
const currentAuthor = ref(null)

// 搜索表单
const searchForm = reactive({
  name: '',
  nationality: '',
  status: null
})

// 分页信息
const pagination = reactive({
  pageNo: 1,
  pageSize: 10,
  total: 0
})

// 获取作者列表
const getAuthorList = async () => {
  try {
    loading.value = true
    const params = {
      ...searchForm,
      pageNo: pagination.pageNo,
      pageSize: pagination.pageSize
    }

    const result = await authorApi.getList(params)

    if (result) {
      tableData.value = result.result || []
      pagination.total = result.total || 0
    }
  } catch (error) {
    ElMessage.error('获取作者列表失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.pageNum = 1
  getAuthorList()
}

// 重置搜索
const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = key === 'status' ? null : ''
  })
  pagination.pageNum = 1
  getAuthorList()
}

// 添加作者
const handleAdd = () => {
  router.push('/author/add')
}

// 查看详情
const handleView = (row) => {
  currentAuthor.value = row
  viewDialogVisible.value = true
}

// 编辑作者
const handleEdit = (row) => {
  router.push(`/author/edit/${row.id}`)
}

// 删除作者
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除作者"${row.name}"吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await authorApi.delete(row.id)
    ElMessage.success('删除成功')
    getAuthorList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败: ' + error.message)
    }
  }
}

// 批量删除
const handleBatchDelete = async () => {
  try {
    const ids = selectedRows.value.map(row => row.id)
    const names = selectedRows.value.map(row => row.name).join('、')

    await ElMessageBox.confirm(
      `确定要删除选中的${ids.length}个作者（${names}）吗？`,
      '批量删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await authorApi.deleteBatch(ids)
    ElMessage.success('批量删除成功')
    getAuthorList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除失败: ' + error.message)
    }
  }
}

// 表格选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 分页大小变化
const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.pageNum = 1
  getAuthorList()
}

// 当前页变化
const handleCurrentChange = (page) => {
  pagination.pageNum = page
  getAuthorList()
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return '-'
  return new Date(date).toLocaleDateString('zh-CN')
}

// 格式化日期时间
const formatDateTime = (datetime) => {
  if (!datetime) return '-'
  return new Date(datetime).toLocaleString('zh-CN')
}

// 组件挂载时获取数据
onMounted(() => {
  getAuthorList()
})
</script>

<style scoped>
.author-list {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
}

.search-section {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.search-form {
  margin-bottom: 0;
}

.text-right {
  text-align: right;
}

.table-section {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.pagination-section {
  display: flex;
  justify-content: center;
}

.author-detail .biography {
  max-height: 100px;
  overflow-y: auto;
  line-height: 1.6;
}
</style>
